package com.powermgr.boringtest.service.impl;

import com.powermgr.boringtest.service.IDownLoadService;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

import static com.powermgr.boringtest.utils.ConfigUtils.PR_REPORTS;

/**
 * DownLoadServiceImpl
 *
 * @author qiuxiangdong
 * @date 2023/8/1 16:43
 */
@Service
public class DownLoadServiceImpl implements IDownLoadService {
    @Override
    public void downLoad(String path, HttpServletResponse response) {
        try {
            InputStream inputStream = Files.newInputStream(Paths.get(PR_REPORTS + File.separator + path + ".zip"));
            response.reset();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(path +".zip", "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
